package com.ming.common.config.file;

import com.github.tobato.fastdfs.domain.fdfs.StorageNode;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.github.tobato.fastdfs.service.TrackerClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import java.io.InputStream;
import java.util.HashSet;


@Configuration
@EnableConfigurationProperties(UploadProperties.class) // 将UploadProperties 对象放在ioc 里面
public class FileService {

    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    @Autowired
    private TrackerClient trackerClient;

    /**
     * 文件上传成功后:
     * 1 地址怎么得      return "http://" + ip + ":" + nginxPort + "/" + storePath.getFullPath();
     * 2 负载均衡怎么实现  /etc/fdfs/tracker.conf 里面的:   store_lookup= 0 (轮询) 1 (指定机器) 2 (选择磁盘空间大的一个)
     *
     * @param in
     * @param fileSize
     * @param extName
     * @return
     */
    public String uploadFile(InputStream in, long fileSize, String extName) {
        // 上传文件到fastdfs 里面
        StorePath storePath = fastFileStorageClient.uploadFile(in, fileSize, extName, new HashSet<>());
        String group = storePath.getGroup();
        // 使用group 确实能得到很多的storage的地址,但是每个storage 里面的文件相同
        StorageNode storeStorage = trackerClient.getStoreStorage(group);
        // Storage的ip 地址
        String ip = storeStorage.getIp();
        //Storage监听的端口 23000/23001 nginx的端口
        int port = storeStorage.getPort();
        int nginxPort = "g1".equals(group) ? 8080 : 8081;
        return "http://" + ip + ":" + nginxPort + "/" + storePath.getFullPath();
    }
}
